package com.ultrasoft.farmasoft.web;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ultrasoft.farmasoft.domain.Country;
import com.ultrasoft.farmasoft.domain.Locality;
import com.ultrasoft.farmasoft.domain.Pharmacy;
import com.ultrasoft.farmasoft.domain.Pharmacystock;
import com.ultrasoft.farmasoft.domain.Provider;
import com.ultrasoft.farmasoft.domain.Providerpharmacy;
import com.ultrasoft.farmasoft.domain.Region;
import com.ultrasoft.farmasoft.domain.Stock;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.service.CustomersService;
import com.ultrasoft.farmasoft.service.HumanResourcesService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;

@Controller
@SessionAttributes({"s_UserPharmacy"}) 
@RequestMapping(value="/Customers")
public class ConfigCustomersController {
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	
	private final CustomersService customerService;
	private final HumanResourcesService humanResourcesService;
	
	private String countryId_		= "_countryId";
	private String regionId_		= "_regionId";
	private String typePharmacy_	= "_typePharmacy";
	private String tempPharmacyId_	= "_tempPharmacyId";
	private String tempLocalityId_ 	= "_tempLocalityId";
	
	@Autowired
	public ConfigCustomersController(CustomersService customerService,HumanResourcesService humanResourcesService) {
		this.customerService = customerService;
		this.humanResourcesService = humanResourcesService;
	}
	
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	private String redirectClient(HttpServletRequest request){
		if(!sessionControl(request))
			return "redirect:/index"; 
		else
			return "redirect:/Customers/client?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}	
	private String handleRedirectClient(HttpServletRequest request,String headMain) {
    	try {
    		return "redirect:/"+headMain+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+
    				"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_)+
    				"&"+UtilCommon.optionId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.optionId_); 
		} catch (Exception e) {
			return redirectClient(request);
		}
    }
	@RequestMapping(value="/client", method=RequestMethod.GET)
	public String handleRequestClient(HttpServletRequest request, Model model) throws ServletException {
		return UtilCommon.fConfiguration_Customers+"mainCustomers";
	}
	@RequestMapping(value="/pharmacies", method=RequestMethod.GET)
	public String handleRequestPharmacies(HttpServletRequest request, Model model) throws ServletException {
		if(sessionControl(request)){
			short tempCountryId=UtilConverter.converterStringToShort(request,countryId_);
			List<Country> listCountry = customerService.getListCountry();
			if(tempCountryId == (short)-1){
				if(!listCountry.isEmpty()){
					Country c = listCountry.get(0);
					List<Region> listRegion = customerService.getListRegion(c.getCountryId());
					if(!listRegion.isEmpty()){
						return handleRedirectClient(request,"Customers/pharmacies?")+"&"+countryId_+"="+c.getCountryId();
					}
				}
			}else{
				List<Region> listRegion = customerService.getListRegionByCountryIdInLocality(tempCountryId);
				if(!listCountry.isEmpty()){
					Country c=customerService.searchCountryByCountryId(tempCountryId);					
					model.addAttribute("listRegion",listRegion);
					model.addAttribute("nameCountry",c.getName());
					model.addAttribute(countryId_,tempCountryId);
					model.addAttribute("listCountry",listCountry);
					
					int tempRegionId=UtilConverter.converterStringToInteger(request,regionId_);
					if(tempRegionId != -1){
						model.addAttribute("listPharmacy",customerService.getListPharmacy(tempRegionId,true));
						model.addAttribute("listPharmacyInactive",customerService.getListPharmacy(tempRegionId,false));
						model.addAttribute(regionId_,tempRegionId);
					}
					return UtilCommon.fConfiguration_Customers_Pharmacies+"pharmacies";
				}
			}	
		}	
		return redirectClient(request);
	}	
	@RequestMapping(value="/pharmaciesNew", method=RequestMethod.GET)
	public String handleRequestPharmaciesNew(HttpServletRequest request, Model model) throws ServletException {
		if(sessionControl(request)){			
			int regionId = UtilConverter.converterStringToInteger(request,regionId_);
			Region region = customerService.searchRegionByRegionId(regionId);			
			model.addAttribute("region",region);
			
			model.addAttribute("pharmacy",new Pharmacy());
			model.addAttribute("listLocality",customerService.getListLocalityByRegionIdByActive(regionId,true));
			model.addAttribute("listPhapharmacy",customerService.getListPharmacy(true));
			return UtilCommon.fConfiguration_Customers_Pharmacies+"formPharmacies";
		}	
		return redirectClient(request);
	}
	@RequestMapping(value="/pharmaciesNew" , method = RequestMethod.POST)
    public String onSubmitRequestPharmaciesNew(@Valid Pharmacy pharmacy, BindingResult result,Model model,@RequestParam String action,HttpServletRequest request){
		if( !action.equals("Cancelar") && sessionControl(request)){   
			Locality l = customerService.searchLocalityByRegionIdByLocalityId(UtilConverter.converterStringToInteger(request,regionId_), UtilConverter.converterStringToShort(request,tempLocalityId_));
			if(l != null){
				if(UtilConverter.converterStringToInteger(request,typePharmacy_) == 2)	// verify is (branch or central)
					pharmacy.setPhapharmacyId(customerService.searchPharmacyByPharmacyId(UtilConverter.converterStringToInteger(request,tempPharmacyId_)));					
				pharmacy.setClient(true);
				pharmacy.setActive(true);				
				pharmacy.setLocality(l);
				customerService.addPharmacy(pharmacy);
				
				Stock s = new Stock(null,"Almacen-"+pharmacy.getName());
				Userpharmacy up = humanResourcesService.searchUserPharmacyByPharmacyIdByUserId(s_pharmacyId,s_userId);
				s.setUserpharmacy(up);
				customerService.addStock(s);

				customerService.addPharmacyStock(new Pharmacystock(pharmacy,s, true));
				
				Provider provider = new Provider(null,"Proveedor-"+pharmacy.getName(),true);
				provider.setActive(true);
				customerService.addProvider(provider);
				
				customerService.addProviderPharmacy(new Providerpharmacy(provider, pharmacy));
			}			
			return handleRedirectClient(request,"Customers/pharmacies?")+"&"+countryId_+"="+UtilConverter.converterStringToShort(request,countryId_)+"&"+regionId_+"="+UtilConverter.converterStringToShort(request,regionId_);
		}else
			return handleRedirectClient(request,"Customers/pharmacies?");	
    }	
	@RequestMapping(value="/pharmaciesEdit", method=RequestMethod.GET)
	public String handleRequestPharmaciesEdit(HttpServletRequest request, Model model) throws ServletException {
		if(sessionControl(request)){
			int pId = UtilConverter.converterStringToInteger(request,UtilCommon.pharmacyId_);
			if( pId != -1){
				int regionId = UtilConverter.converterStringToInteger(request,regionId_);
				Region region = customerService.searchRegionByRegionId(regionId);			
				model.addAttribute("region",region);
				
				Pharmacy p = customerService.searchPharmacyByPharmacyId(pId);
				if(p.getPhapharmacyId() != null)
					model.addAttribute("tempPhapharmacyId",p.getPhapharmacyId().getPharmacyId());
				model.addAttribute("pharmacy",p);
				model.addAttribute("listLocality",customerService.getListLocalityByRegionIdByActive(UtilConverter.converterStringToInteger(request,regionId_),true));
				model.addAttribute("listPhapharmacy",customerService.getListPharmacy(true));
				return UtilCommon.fConfiguration_Customers_Pharmacies+"formPharmacies";
			}
		}	
		return redirectClient(request);
	}
	@RequestMapping(value="/pharmaciesEdit" , method = RequestMethod.POST)
    public String onSubmitRequestPharmaciesEdit(@Valid Pharmacy pharmacy, BindingResult result,Model model,@RequestParam String action,HttpServletRequest request){
		if( !action.equals("Cancelar") && sessionControl(request)){   
			Locality l = customerService.searchLocalityByRegionIdByLocalityId(UtilConverter.converterStringToInteger(request,regionId_), UtilConverter.converterStringToShort(request,tempLocalityId_));
			if(l != null){
				Pharmacy p = customerService.searchPharmacyByPharmacyId(pharmacy.getPharmacyId());
				if(UtilConverter.converterStringToInteger(request,typePharmacy_) == 2)
					p.setPhapharmacyId(customerService.searchPharmacyByPharmacyId(UtilConverter.converterStringToInteger(request,tempPharmacyId_)));
				if(UtilConverter.converterStringToInteger(request,typePharmacy_) == 1)
					p.setPhapharmacyId(null);
				p.setLocality(l);
				p.setName(pharmacy.getName());
				p.setSocialReason(pharmacy.getSocialReason());
				p.setNit(pharmacy.getNit());
				p.setAddress(pharmacy.getAddress());
				p.setEmail(pharmacy.getEmail());				
				customerService.updatePharmacy(p);				
			}			
			return handleRedirectClient(request,"Customers/pharmacies?")+"&"+countryId_+"="+UtilConverter.converterStringToShort(request,countryId_)+"&"+regionId_+"="+UtilConverter.converterStringToShort(request,regionId_);
		}else
			return handleRedirectClient(request,"Customers/pharmacies?");	
    }
	@RequestMapping(value = "/ajaxGiveLowOrHighToPharmacy", method = RequestMethod.GET)
	public @ResponseBody String handleRequestajAxGiveLowOrHighToPharmacy(@RequestParam Integer pharmacyId,@RequestParam boolean active){
		Pharmacy p = customerService.searchPharmacyByPharmacyId(pharmacyId);
		p.setActive(active);
		customerService.updatePharmacy(p);
        String lowHigh = "";
        if(active)
        	lowHigh = " Se dio de Alta a ";
        else
        	lowHigh = " Se dio de Baja a ";
        return lowHigh;
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	@RequestMapping(value="/provider", method=RequestMethod.GET)
	public String handleRequestProvider(HttpServletRequest request, Model model) throws ServletException {
		return UtilCommon.fConfiguration_Customers_Provider+"provider";
	}
}
